package com.yuchengtech.simpleServer.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.InputSource;
import com.yuchengtech.fileUtil.FileUtil;
import com.yuchengtech.simpleServer.core.exception.SimpleServerException;


public class ServletConfig {
		private HashMap<String,ServletBean> servletMap;
		private static boolean inited;
		
		private ServletConfig()
		{
			servletMap=new HashMap<String, ServletBean>();
		}

		public void addServletBean(ServletBean bean)
		{
			servletMap.put(bean.getName(), bean);
		}

		
		public HashMap<String, ServletBean> getServletMap() {
			return servletMap;
		}
		
	public static ServletConfig readServletConfig() throws SimpleServerException
	{
		if (inited) {
			System.out.println("WoxConfig Already initialed");
			return null;
		}
		ServletConfig config=new ServletConfig();
		InputSource is=null;
		try {
			 File file=new File(FileUtil.contactPath(FileUtil.getRunPath(),"config/servlets.xml"));
			 if(file.exists()&&file.isFile()){
				 FileInputStream fis=new FileInputStream(file);
				 is=new InputSource(fis);
			 }else
				 throw new SimpleServerException("servlet config file is not found!");
		} catch (FileNotFoundException e1) {
			throw new SimpleServerException("servlet config file is not found!");
		}
		Digester digester = 
			DigesterLoader.createDigester(ServletConfig.class
					.getClassLoader()
					.getResource("com/yuchengtech/simpleServer/servlet/servlet-rule.xml"));
		//push
		digester.push(config);
		//parse
		try {
			digester.parse(is);
		} catch (Exception e) {
			e.printStackTrace();
			throw new SimpleServerException("servlet读取配置文件失败");
		}
		
		//增加默认的两个servlet
		ServletBean jsonServlet=new ServletBean();
		jsonServlet.setName("jsonBack_wox");
		jsonServlet.setClassPath("com.yuchengtech.simpleServer.servlet.JsonServlet");
		config.addServletBean(jsonServlet);
		
		ServletBean defaultServlet=new ServletBean();
		defaultServlet.setName("default_servlet");
		defaultServlet.setClassPath("com.yuchengtech.simpleServer.servlet.DefaultServlet");
		config.addServletBean(defaultServlet);
		/*
		ServletBean fileServlet=new ServletBean();
		fileServlet.setName("fileServlet_ss.ser");
		fileServlet.setClassPath("com.yuchengtech.simpleServer.servlet.FileServlet");
		config.addServletBean(fileServlet);
		*/
		inited=true;
		return config;
	}
	
}
